<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import MonacoEditor from '../../components/MonacoEditor.vue';
import { useEditorStore } from '../../stores/editor';
import { subscribe, theme as themeStore } from '../../assets/theme';
import { useAiTimelineWatcher } from './composables/useAiTimelineWatcher';

const props = defineProps({
  tab: { type: Object, required: true },
  groupId: { type: [String, Number], required: true },
  isActive: { type: Boolean, default: false },
  // 接收但不直接使用，优先采用全局主题订阅
  theme: { type: String, default: 'vs-dark' }
});

const emit = defineEmits(['editor-ready', 'content-change', 'cursor-change', 'diff-updated', 'accept-change', 'reject-change']);

const editorStore = useEditorStore();

// AI时间线监听器 - 自动切换编辑器模式
const aiTimelineWatcher = useAiTimelineWatcher(props.tab);

// 主题：订阅全局主题并映射到 Monaco 主题
const monacoTheme = ref('vs-dark');
let unsub = () => {};
function applyMonacoThemeByStore() {
  try {
    const isDark = themeStore.colorTheme === 'dark' || (themeStore.colorTheme === 'system' && document.documentElement.classList.contains('dark'));
    monacoTheme.value = isDark ? 'vs-dark' : 'vs';
  } catch { monacoTheme.value = 'vs-dark'; }
}
onMounted(() => { applyMonacoThemeByStore(); unsub = subscribe(() => applyMonacoThemeByStore()); });
onBeforeUnmount(() => { try { unsub?.(); } catch {} });

// 将全局/设置中的编辑器选项传递给子组件（单编辑器/修改端通用）
const editorOptions = computed(() => ({
  fontSize: editorStore.fontSize || 14,
  wordWrap: editorStore.wordWrap || 'off',
  automaticLayout: true,
  minimap: { enabled: editorStore.minimapEnabled || false },
  scrollBeyondLastLine: false,
  renderWhitespace: editorStore.renderWhitespace || 'none',
  tabSize: editorStore.tabSize || 4,
  insertSpaces: editorStore.insertSpaces !== false,
  detectIndentation: true,
  folding: true,
  lineNumbers: 'on',
  readOnly: editorStore.readOnly || false,
  glyphMargin: true,
  contextmenu: true,
  mouseWheelZoom: true,
  smoothScrolling: true,
  cursorBlinking: 'blink',
  cursorSmoothCaretAnimation: 'on'
}));

// Diff 相关 - 集成AI时间线自动切换
const useDiff = computed(() => {
  // 优先使用tab的showingDiff状态（可能由AI时间线监听器自动设置）
  const result = !!props.tab?.showingDiff;
  console.log('[NewTabContent] useDiff computed:', result, 'tab.showingDiff:', props.tab?.showingDiff);
  return result;
});

const originalText = computed(() => {
  // 优先使用由AI时间线聚合得到的original内容（systemHistoryDiff），其次回退到最新记录的beforeContent
  const sysOriginal = props.tab?.systemHistoryDiff?.originalContent;
  const aiOriginal = props.tab?.aiStatus?.latestEntry?.beforeContent;
  const savedOriginal = props.tab?.savedContent;
  
  return String(sysOriginal ?? aiOriginal ?? savedOriginal ?? '');
});
const modifiedText = computed(() => (props.tab?.content ?? '') + '');
const diffEditorOptions = computed(() => ({
  renderSideBySide: props.tab?.diffSideBySide !== false, // 默认并排，若显式为 false 则内联
  originalEditable: false,
  readOnly: editorStore.readOnly || false,
  // 与单编辑器通用的一些选项
  fontSize: editorStore.fontSize || 14,
  wordWrap: editorStore.wordWrap || 'off',
  minimap: { enabled: editorStore.minimapEnabled || false },
}));

// 处理接受变更
const handleAcceptChange = ({ change, index }) => {
  console.log('接受变更:', change, index);
  emit('accept-change', { change, index, tab: props.tab });
};

// 处理拒绝变更
const handleRejectChange = ({ change, index }) => {
  console.log('拒绝变更:', change, index);
  emit('reject-change', { change, index, tab: props.tab });
};
</script>

<template>
  <div class="tab-content w-full h-full relative">
    <!-- Debug info -->
    <div v-if="false" class="debug-info">
      useDiff: {{ useDiff }}, isActive: {{ isActive }}, tab.id: {{ tab?.id }}
    </div>
    <MonacoEditor
      :key="(useDiff ? 'diff:' : 'plain:') + (tab?.id || tab?.path || '') + ':' + (tab?.editorRerenderKey || '')"
      :use-diff="useDiff"
      :original-content="originalText"
      :content="modifiedText"
      :ext="tab.ext || ''"
      :isActive="isActive"
      :theme="monacoTheme"
      :editor-options="editorOptions"
      :diff-editor-options="diffEditorOptions"
      @editor-ready="payload => { console.log('[NewTabContent] editor-ready event'); emit('editor-ready', payload); }"
      @content-change="val => { console.log('[NewTabContent] content-change event, length:', val?.length || 0); emit('content-change', val); }"
      @cursor-change="pos => emit('cursor-change', pos)"
      @diff-updated="changes => emit('diff-updated', changes)"
      @accept-change="handleAcceptChange"
      @reject-change="handleRejectChange"
    />
  </div>
</template>

<style scoped>
.tab-content { min-height: 0; flex: 1; }
</style>